package com.laf.framework.aspectj;

import com.laf.common.constant.CacheConstants;
import com.laf.common.core.redis.RedisCache;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用于处理浏览量新增的
 */
@Component
@Aspect // 标记该类是一个切面类
public class HitsAspect {

    @Autowired
    private RedisCache redisCache;

    // 1. 定义切点表达式,对带有 HitsAnnotation 方法进行增强
    @Pointcut("@annotation(com.laf.common.annotation.HitsAnnotation)")
    public void pointCut() {
    }

    // 2. 定义成功的后置通知处理方法
    @AfterReturning(value = "pointCut()")
    public void afterReturning(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        Long id = (Long) args[0];
        Object cacheMapValue = redisCache.getCacheMapValue(CacheConstants.HITS_PREFIX, id.toString());
        boolean b = cacheMapValue != null;
        if (!b) {
            // 新增缓存 ： key为动态id  value 为浏览量
            redisCache.setCacheMapValue(CacheConstants.HITS_PREFIX, id.toString(), 1);
        } else {
            // 缓存存在，则浏览量+1
            redisCache.setCacheMapValue(CacheConstants.HITS_PREFIX, id.toString(), (Integer) cacheMapValue + 1);
        }


    }


}
